import React from 'react';
import { InputNumber } from 'antd';
import produce from 'immer';
import classNames from 'classnames';
import styles from './index.less';

const Index = (props) => {
  const {
    type, // 格式类型，'$'、'%' 或 '无'。 优先级高，生效时 formatter、parser 属性将会失效
    formatter,
    parser,

    disabled,
    value,
    ...rest
  } = props;

  const { formatter: newFormatter, parser: newParser } = produce(
    {
      formatter,
      parser,
    },
    (draftState) => {
      if (type === '$') {
        draftState.formatter = (newValue) => `$ ${newValue}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        draftState.parser = (newValue) => newValue.replace(/\$\s?|(,*)/g, '');
      } else if (type === '%') {
        draftState.formatter = (newValue) => `${newValue}%`;
        draftState.parser = (newValue) => newValue.replace('%', '');
      }
      return draftState;
    },
  );

  if (!Object.keys(props).includes('value')) {
    return 'DEPRECATED';
  }

  if (disabled && disabled.render) {
    return (
      disabled.render(newFormatter ? newFormatter(value) : value, {
        value,
        formatter: newFormatter,
      }) || <span>&nbsp;</span>
    );
  }

  return (
    <span className={classNames(styles.col24, styles.componentWrapper)}>
      <InputNumber
        style={{ width: '100%' }}
        {...rest}
        formatter={newFormatter}
        parser={newParser}
        disabled={!!disabled}
        value={value}
      />
    </span>
  );
};

Index.displayName = 'InputNumber';
export default Index;
